package com.threegroup.android3grouppersonality.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.PermissionChecker;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.threegroup.android3grouppersonality.R;
import com.threegroup.android3grouppersonality.pojo.Blog;
import com.threegroup.android3grouppersonality.utils.ImageTool;
import com.threegroup.android3grouppersonality.utils.Permissions;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BlogPublishActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int IMG_COUNT = 8;
    private static final String IMG_ADD_TAG = "a";
    private GridView gridView;
    private GVAdapter adapter;
    private TextView send;
    private ImageView img;
    private List<String> list;
    private Spinner spinner;
    private EditText pub_content;
    private String contentImgName="";
    private Editable editable;
    private Map<String,String> fileMap = new HashMap<>();
    private Map<String, File> imageMap = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blog_publish);
        Permissions.verifyStoragePermissions(this);
        initView();
        initData();
        initEvent();
    }
    //初始化组件
    private void initView() {
        send=findViewById(R.id.send);
        gridView = (GridView) findViewById(R.id.gridview);
        spinner=(Spinner)findViewById(R.id.sb_blogtype) ;
        String[] arry={"体育","娱乐","军事","国际","游戏"};
        ArrayAdapter<String> adapter=new ArrayAdapter<>(this,R.layout.support_simple_spinner_dropdown_item,arry);
        spinner.setAdapter(adapter);
        pub_content=findViewById(R.id.pub_content);
    }

    //初始化组件事件
    private void initEvent() {
       send.setOnClickListener(this);
    }

    //组件点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send:
                publishBlog();
                break;

        }

    }

    private void publishBlog() {
       /* SharedPreferences spf=getSharedPreferences("share",MODE_PRIVATE);
        String type=spf.getString("type","");
        if(type==""){
            Toast.makeText(BlogPublishActivity.this, "请先登录!", Toast.LENGTH_SHORT).show();
            return;
        }*/
        final String content = pub_content.getText().toString();
        final Map<String, File> fileMap = uploadNew(content);
        Blog blog=new Blog();
        blog.setContent(content);
    }

    private void upLoad() {
        Bitmap bitmap;
        Bitmap bmpCompressed;
        for (int i = 0; i < list.size() - 1; i++) {

            String str1=list.get(i).substring(0, list.get(i).indexOf("/"));
            String str2=list.get(i).substring(str1.length()+1, list.get(i).length());
            bitmap = BitmapFactory.decodeFile(list.get(i));
            bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bmpCompressed.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            System.out.println(data);
        }

    }

    private void initData() {
        if (list == null) {
            list = new ArrayList<>();
            list.add(IMG_ADD_TAG);
        }
        adapter = new GVAdapter();
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list.get(position).equals(IMG_ADD_TAG)) {
                    if (list.size() < IMG_COUNT) {
                        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, 0);
                    } else
                        Toast.makeText(BlogPublishActivity.this, "最多只能选择7张照片！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        refreshAdapter();
    }

    private void refreshAdapter() {
        if (list == null) {
            list = new ArrayList<>();
        }
        if (adapter == null) {
            adapter = new GVAdapter();
        }
        adapter.notifyDataSetChanged();
    }

    private class GVAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplication()).inflate(R.layout.activity_add_photo_gv_items, parent, false);
                holder = new ViewHolder();
                holder.imageView = (ImageView) convertView.findViewById(R.id.main_gridView_item_photo);
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.main_gridView_item_cb);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            String s = list.get(position);
            if (!s.equals(IMG_ADD_TAG)) {
                holder.checkBox.setVisibility(View.VISIBLE);
                holder.imageView.setImageBitmap(ImageTool.createImageThumbnail(s));
            } else {
                holder.checkBox.setVisibility(View.GONE);
                holder.imageView.setImageResource(R.drawable.ic_photo_upload);
            }
            holder.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.remove(position);
                    refreshAdapter();
                }
            });
            return convertView;
        }

        private class ViewHolder {
            ImageView imageView;
            CheckBox checkBox;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            System.out.println("data null");
            return;
        }
        if (requestCode == 0) {
            final Uri uri = data.getData();
            String path = ImageTool.getImageAbsolutePath(this, uri);
            String suffix = path.substring(path.lastIndexOf("."));
            String fileName = getFileName() + suffix;
            fileMap.put(fileName,path);

            Bitmap bitmap= BitmapFactory.decodeFile(path);
            insertBitmap(bitmap,fileName);

            if (list.size() == IMG_COUNT) {
                removeItem();
                refreshAdapter();
                return;
            }
            removeItem();
            contentImgName=path+",";
            list.add(path);
            list.add(IMG_ADD_TAG);
            refreshAdapter();
        }
    }

    private void removeItem() {
        if (list.size() != IMG_COUNT) {
            if (list.size() != 0) {
                list.remove(list.size() - 1);
            }
        }
    }
    //生成"yyyyMMddHHmmss"格式的字符串
    private String getFileName() {
        java.text.SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        return simpleDateFormat.format(date);
    }

    private void insertBitmap(Bitmap bitmap,String fileName) {
        String btmpTag = "<img src="+fileName+"/>";
        SpannableString spannableString = new SpannableString(btmpTag);

        int width = pub_content.getWidth();
        Bitmap zoomBtmp = zoomBitmap(width,bitmap);
        ImageSpan imageSpan = new ImageSpan(this,zoomBtmp);

        spannableString.setSpan(imageSpan,0,btmpTag.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (editable==null){
            editable = pub_content.getText();
        }
        int start = pub_content.getSelectionStart();
        start = start>editable.length()?editable.length():start;
        editable.insert(start,spannableString);
        pub_content.setText(editable);
    }
    private Bitmap zoomBitmap(int width, Bitmap bitmap){
        int btmpWidth = bitmap.getWidth();
        int btmpHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scale = (float) width/btmpWidth;
        matrix.setScale(scale,scale);
        Bitmap btmp = Bitmap.createBitmap(bitmap,0,0,btmpWidth,btmpHeight,matrix,true);
        return btmp;
    }

    private Map<String,File> uploadNew(String content) {
        String imgTag="<img src=([\\w/.]*)/>";
        Pattern pattern= Pattern.compile(imgTag);
        Matcher matcher= pattern.matcher(content);
        while (matcher.find()) {
            final String tag = matcher.group();
            String imgName = matcher.group(1);
            imageMap.put(imgName,new File(fileMap.get(imgName)));
        }
        return imageMap;
    }

}
